﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLULearningNetworkModel;
using DLULearningNetwork.Libs;

namespace DLULearningNetwork.ActionFilterAttributes
{
    public class RequireUserLogin : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {            
            if (LoginUser == null)
            {
                filterContext.Result = new RedirectResult("~/Home/Index");
            }

            base.OnActionExecuting(filterContext);
        }

        public static Account LoginUser
        {
            get
            {
                if (LibSession.Get(Constants.ACCOUNT_LOGIN) != null)
                {
                    return (Account)(LibSession.Get(Constants.ACCOUNT_LOGIN));
                }
                else
                {
                    string email = LibCookie.Get(Constants.EMAIL_LOGIN);
                    string password = LibCookie.Get(Constants.PASSWORD_LOGIN);
                    Account acc = Account.Single(email, StringHelper.EncodeMD5(password));
                    if (acc != null)
                    {
                        LibSession.Set(Constants.ACCOUNT_LOGIN, acc);
                        return acc;
                    }
                    return null;
                }
            }
        }
    }
}